const express = require('express');
const router = express.Router();
const { User, Course } = require('../../models');
const { Op, where } = require('sequelize');
const { NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    email: data.email,
    username: data.username,
    password: data.password,
    nickname: data.nickname,
    sex: data.sex,
    company: data.company,
    introduce: data.introduce,
    role: data.role,
    avatar: data.avatar,
  };
};

const conditionParam = {
  include: [
    {
      model: Course,
      as: 'courses',
      attributes: ['id', 'name'],
    },
  ],
};

/**
 * 公共方法: 查询当前用户
 * */

async function getUser(req) {
  const { id } = req.params;
  const user = await User.findByPk(id, conditionParam);
  if (!user) {
    throw new NotFound(`ID: ${id}的用户为找到`);
  }
  return user;
}

/**
 * 查询用户列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      where: {},
      order: [['id', 'DESC']],
      limit: pageSize,
      offset,
    };
    if (query.email) {
      condition.where.email = {
        [Op.eq]: `%${query.email}%`,
      };
    }
    if (query.username) {
      condition.where.username = {
        [Op.eq]: `%${query.username}%`,
      };
    }
    if (query.nickname) {
      condition.where.nickname = {
        [Op.like]: `%${query.nickname}%`,
      };
    }
    if (query.role) {
      condition.where.role = {
        [Op.eq]: `%${query.role}%`,
      };
    }
    console.log(condition, 'condition');
    // const users = await User.findAll(condition);
    const { count: total, rows } = await User.findAndCountAll(condition);
    success(res, '查询成功', {
      users: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询当前登录用户
 * */
router.get('/me', async function (req, res) {
  console.log(req, 999999999999);
  try {
    console.log(req, 'req');
    const user = req.user;
    success(res, '查询成功', { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询用户详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const users = await getUser(req);
    success(res, '查询成功', { users });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建用户
 * */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req.body);
    console.log(body, 'req.body');
    const users = await User.create(body);
    success(res, '创建成功', { users }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新用户
 * */
router.put('/:id', async function (req, res) {
  try {
    const user = await getUser(req);
    const body = filterBody(req.body);
    const data = await user.update(body);
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
